<template>
	<view>
		<u-navbar :autoBack="true" :border="false" :placeholder="true" :title="title">
			<view slot="right">
				<image style="width: 20px; height: 20px;" src="../../static/refresh.svg"
					@click="openBluetoothAdapter()"></image>
			</view>
		</u-navbar>


		<view class="p10 b-b">已连接</view>
		<view class="titleClass countMain" v-show="connectDev.id">
			<view class="titleIcon">
				<image style="width: 20px; height: 20px;" src="../../static/div-checked.svg"></image>
			</view>
			<view class="information">
				<view class="fontTit">{{connectDev.name}}</view>
				<view class="fontSub">{{connectDev.id}}</view>
			</view>
		</view>
		<view class="p10 b-b">附近设备</view>
		<view v-for="(item,index) in showList" class="titleClass countMain" :key="index">
			<view class="titleIcon">
				<image v-if="connectDev.id==item.deviceId" style="width: 20px; height: 20px;"
					src="../../static/div-checked.svg"></image>
				<u-icon name="coupon" v-else size="25"></u-icon>
			</view>
			<view class="information">
				<view class="fontTit">{{item.name}}</view>
				<view class="fontSub">{{item.deviceId}}</view>
			</view>
			<view class="rightBut">
				<button class="mini-btn" type="primary" size="mini" @click="createBLEConnection(item)">配对</button>
			</view>
		</view>
		<view>
			<u-popup :round="10" :show="showBLE" mode="center" @close="close">
				<view class="shareClass" :key="pageNum">
					<view class="title"> 配对成功 </view>
					<view class="shareMain">
						<view> 设备名称： {{ domain.name }}</view>
						<view> 设备地址： {{ domain.deviceId }}</view>
						<!-- <view> 序列号： {{ domain.equipmentData['SN'] }}</view> -->
					</view>
					<view class="shareFoot">
						<view> 是否要保存此设备到本地？</view>
						<view class="shareBut">
							<button type="default" size="mini" @click="cancelBluePop">取消</button>
							<button type="primary" size="mini" @click="preservationBulPop">保存</button>
						</view>
					</view>
				</view>
			</u-popup>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				pageNum: 0,
				title: "蓝牙设备",
				showList: [], //搜寻到的数据
				connectDev: {
					name: '',
					id: '',
				},
				datastr: "",
				flagSub: "",
				flagRefresh: false,
				showBLE: false,
			}
		},
		created() {
			let that = this
			setTimeout(() => {
				that.openBluetoothAdapter();
			}, 500)
			// uni.getConnectedBluetoothDevices({
			// 	success(res) {
			// 		if (res.devices.length > 0) {
			// 			that.connectDev.name = res.devices[0].name
			// 			that.connectDev.id = res.devices[0].deviceId
			// 		}
			// 	}
			// })

		},
		onLoad() {

		},
		onReady() {

		},

		computed: {

		},
		watch: {

		},
		onUnload() {
			this.stopBluetoothDevicesDiscovery()
		},
		methods: {
			/**
			 * 初始化蓝牙设备
			 */
			openBluetoothAdapter() {
				wx.openBluetoothAdapter({
					success: e => {
						console.log('初始化蓝牙成功:' + e.errMsg);
						console.log(JSON.stringify(e));
						this.getBluetoothAdapterState();
					},
					fail: e => {
						if (e.errMsg == 'openBluetoothAdapter:fail already opened') {
							console.log('蓝牙已经开:');
							this.getBluetoothAdapterState();
							return
						}
						console.log('初始化蓝牙失败，错误码：' + (e.errCode || e.errMsg));
						if (e.errCode !== 0) {
							initTypes(e.errCode, e.errMsg);
						}
					}
				});
			},
			/**
			 * 获取本机蓝牙适配器状态
			 */
			getBluetoothAdapterState() {
				uni.getBluetoothAdapterState({
					success: res => {
						console.log(JSON.stringify(res));
						// if(res.errno==0){
						console.log('开始搜索蓝牙设备');
						this.startBluetoothDevicesDiscovery()
						// }
					},
					fail: e => {
						console.log('获取本机蓝牙适配器状态失败，错误码：' + e.errCode);
						if (e.errCode !== 0) {
							initTypes(e.errCode);
						}
					}
				});
			},
			/**
			 * 停止搜索蓝牙设备
			 */
			stopBluetoothDevicesDiscovery() {
				wx.stopBluetoothDevicesDiscovery({
					success: e => {
						console.log('停止搜索蓝牙设备:' + e.errMsg);
					},
					fail: e => {
						console.log('停止搜索蓝牙设备失败，错误码：' + e.errCode);
						if (e.errCode !== 0) {
							initTypes(e.errCode);
						}
					}
				});
			},
			/**
			 * 开始搜索蓝牙设备
			 */
			startBluetoothDevicesDiscovery() {
				wx.startBluetoothDevicesDiscovery({
					success: e => {
						console.log('开始搜索蓝牙设备:' + e.errMsg);
						this.onBluetoothDeviceFound();
						// this.getBluetoothDevices();
					},
					fail: e => {
						console.log('搜索蓝牙设备失败，错误码：' + JSON.stringify(e));
						if (e.errCode !== 0) {
							initTypes(e.errCode);
						}
					}
				});
			},
			/**
			 * 发现外围设备
			 */
			onBluetoothDeviceFound() {
				wx.onBluetoothDeviceFound(devices => {
					console.log('开始监听寻找到新设备的事件', devices, devices.devices[0].name);
					// this.$set(this.disabled, 3, false);
					if (devices.devices[0].name) {
						this.getBluetoothDevices();
					}

				});
			},
			/**
			 * 获取在蓝牙模块生效期间所有已发现的蓝牙设备。包括已经和本机处于连接状态的设备。
			 */
			getBluetoothDevices() {
				let that = this
				uni.showToast({
					title: '正在搜索附近蓝牙设备...',
					icon: 'loading',
					duration: 99999
				});
				wx.getBluetoothDevices({
					success: res => {
						uni.hideToast()
						that.showList = [];
						res.devices.forEach(item => {
							console.log(item.name)
							if (!item.name.startsWith('未知')) {
								that.showList.push(item)
							}
						})
					},
					fail: e => {
						uni.hideToast()
						console.log('获取蓝牙设备错误，错误码：' + e.errCode);
						if (e.errCode !== 0) {
							initTypes(e.errCode);
						}
					}
				});
			},
			/**
			 * 连接低功耗蓝牙
			 */
			createBLEConnection(item) {
				let that = this
				let deviceId = item.deviceId;
				that.domain.deviceId = item.deviceId;
				that.domain.equipmentName = item.name;
				uni.showToast({
					title: '连接蓝牙...',
					icon: 'loading',
					duration: 99999
				});
				uni.createBLEConnection({
					// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
					deviceId,
					success: res => {
						// 连接设备后断开搜索 并且不能搜索设备
						// this.stopBluetoothDevicesDiscovery(true);
						setTimeout(function() {
							// 连接成功后，获取该设备服务列表
							uni.getBLEDeviceServices({
								deviceId: deviceId,
								success(res) {
									that.connectDev.id = item.deviceId
									that.connectDev.name = item.name
									uni.showToast({
										title: '链接成功,获取设备信息...',
										icon: 'loading',
										duration: 99999
									});
									console.log("该设备的服务:", res)
									// 遍历services
									res.services.forEach((item) => {
										let serviceId = item.uuid
										let flag = true
										// 寻找services下notify为true的特征id
										uni.getBLEDeviceCharacteristics({
											deviceId,
											serviceId,
											success: res => {
												res.characteristics
													.forEach(item => {
														if (item
															.properties
															.notify &&
															flag) {
															uni.showToast({
																title: '获取成功',
																icon: 'loading',
																duration: 1000
															});
															that.domain
																.serviceId =
																serviceId
															that.domain
																.characteristicWatchId =
																item
																.uuid;
															that.domain
																.characteristicId =
																item
																.uuid;
															flag =
																false
															console
																.log(
																	"找到Service: ServiceId" +
																	that
																	.domain
																	.serviceId
																)
															console
																.log(
																	"找到Service: characteristicId" +
																	that
																	.domain
																	.characteristicId
																)
														}
													})
											},
										});
									})
								}
							})
						}, 1000)
					},
					fail: e => {
						console.log('连接低功耗蓝牙失败，错误码：' + JSON.stringify(e));
						uni.hideToast();
						if (e.errCode !== 0) {
							initTypes(e.errCode);
						}
					}
				});
			},
		}
	};
	/**
	 * 判断初始化蓝牙状态
	 */
	function initTypes(code, errMsg) {
		switch (code) {
			case 10000:
				toast('未初始化蓝牙适配器');
				break;
			case 10001:
				toast('未检测到蓝牙，请打开蓝牙重试！');
				break;
			case 10002:
				toast('没有找到指定设备');
				break;
			case 10003:
				toast('连接失败');
				break;
			case 10004:
				toast('没有找到指定服务');
				break;
			case 10005:
				toast('没有找到指定特征值');
				break;
			case 10006:
				toast('当前连接已断开');
				break;
			case 10007:
				toast('当前特征值不支持此操作');
				break;
			case 10008:
				toast('其余所有系统上报的异常');
				break;
			case 10009:
				toast('Android 系统特有，系统版本低于 4.3 不支持 BLE');
				break;
			default:
				toast(errMsg);
		}
	}

	/**
	 * 弹出框封装
	 */
	function toast(content, showCancel = false) {
		uni.showModal({
			title: '提示',
			content,
			showCancel
		});
	}
</script>

<style lang="scss">
	.titleClass {
		display: flex;
		flex-direction: row;
		padding: 10px 0;
	}

	.titleIcon {
		padding: 10px 20px;
	}

	.information {
		width: 80%;
		padding-top: 5px;
	}

	.rightBut {
		width: 100px;
		padding: 10px 20px;
	}

	.shareClass {
		width: 300px;
		height: 250px;

		.title {
			width: 100%;
			line-height: 40px;
			text-align: center;
			border-bottom: 1px solid #ebeef5;
		}

		.shareMain {
			display: flex;
			flex-direction: column;
			line-height: 30px;
			padding: 10px;
		}

		.shareFoot {
			padding: 0 10px;

			.shareBut {
				display: flex;
				padding: 20px 0px;
			}
		}
	}
</style>